package concurrency.chapter10;

import java.util.Optional;
import java.util.stream.Stream;

/**
 * 30讲-如何实现一个自己的显式锁Lock精讲
 */
public class LockTest {
    public static void main(String[] args) throws InterruptedException {
        final BooleanLock booleanLock = new BooleanLock();
        Stream.of("T1", "T2", "T3", "T4").forEach(
                name -> new Thread(() -> {
                    try {
                        //从lock方法里出来就释放了"标识锁"initValue，没有notify，所以其他线程没有抢"标识锁"initValue
                        //booleanLock.lock();
                        booleanLock.lock(10);
                        Optional.of(Thread.currentThread().getName() + " have a lock monitor").ifPresent(System.out::println);
                        work();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (Lock.TimeOutException e) {
                        Optional.of(Thread.currentThread().getName() + " time out").ifPresent(System.out::println);
                    }finally {
                        booleanLock.unlock();
                    }
                }, name).start()
        );
        //Thread.sleep(100);
        //任何线程都可以释放锁，严重的bug
        //必须谁加的锁，就是谁去释放
        //booleanLock.unlock();
    }

    private static void work() throws InterruptedException {
        Optional.of(Thread.currentThread().getName() + " is working...").ifPresent(System.out::println);
        Thread.sleep(3_000);
    }
}
